package com.example.egcar1.controller;

import com.example.egcar1.base.response.JsonResult;
import com.example.egcar1.base.response.StatusCode;
import com.example.egcar1.mapper.UserMapper;
import com.example.egcar1.pojo.dto.UserLoginParam;
import com.example.egcar1.pojo.dto.UserRegParam;
import com.example.egcar1.pojo.entity.User;
import com.example.egcar1.pojo.vo.UserLoginVo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/v1/user")
@Api(tags = "用户管理")
public class UserController {
    @Autowired(required = false)
    private UserMapper userMapper;

    @PostMapping("/reg")
    @ApiOperation("用户注册")
    @ApiOperationSupport(order = 10)
    public JsonResult regUser(@RequestBody UserRegParam userRegParam) {
        log.debug("userRegParam={}", userRegParam);
        if (userMapper.selectUserByUsername(userRegParam.getUsername()) > 0) {
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insertUser(user);

        return JsonResult.ok();
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    @ApiOperationSupport(order = 20)
    public JsonResult loginUser(@RequestBody UserLoginParam userLoginParam, @ApiIgnore HttpSession session) {
        log.debug("userLoginParam={}", userLoginParam);
        UserLoginVo userLoginVo = userMapper.selectUserByUsernameAndPassword(userLoginParam.getUsername(),
                userLoginParam.getPassword());

        if (userLoginVo == null) {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user", userLoginVo);
        return JsonResult.ok(userLoginVo);
    }

    @GetMapping("/currentUser")
    @ApiOperation("获取当前用户")
    @ApiOperationSupport(order = 30)
    public JsonResult getCurrentUser(@ApiIgnore HttpSession session){
        UserLoginVo userLoginVo = (UserLoginVo) session.getAttribute("user");
        if(userLoginVo==null){
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
        return JsonResult.ok(userLoginVo);
    }
    @GetMapping("/logout")
    @ApiOperation("用户登出")
    @ApiOperationSupport(order = 40)
    public JsonResult logOut(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.ok();
    }

}
